const { pool } = require('../config/db');
const { success, error } = require('../utils/response');

exports.getList = async (req, res, next) => {
  try {
    const [books] = await pool.query(
      `SELECT b.* FROM bookshelf bs 
       JOIN books b ON bs.book_id = b.id 
       WHERE bs.user_id = ? 
       ORDER BY bs.id DESC`,
      [req.userId]
    );

    success(res, books);
  } catch (err) {
    next(err);
  }
};

exports.add = async (req, res, next) => {
  try {
    const { bookId } = req.body;
    const userId = req.userId;

    console.log('📖 书架添加请求:', { bookId, userId, bookIdType: typeof bookId });

    // 检查用户是否已登录
    if (!userId) {
      console.log('❌ 用户未登录');
      return error(res, '用户未登录', 401);
    }

    // 参数验证
    if (!bookId) {
      console.log('❌ 缺少图书ID参数');
      return error(res, '缺少图书ID参数', 400);
    }

    const bookIdNum = parseInt(bookId);
    console.log('📖 解析后的bookId:', bookIdNum, '原始值:', bookId);

    if (isNaN(bookIdNum) || bookIdNum <= 0) {
      console.log('❌ 无效的图书ID:', bookId, '解析结果:', bookIdNum);
      return error(res, '无效的图书ID', 400);
    }

    // 检查书籍是否存在
    console.log('📖 检查书籍是否存在，bookIdNum:', bookIdNum);
    const [books] = await pool.query('SELECT id, name FROM books WHERE id = ?', [bookIdNum]);
    console.log('📖 书籍查询结果:', books);

    if (books.length === 0) {
      console.log('❌ 图书不存在，bookId:', bookIdNum);
      return error(res, '图书不存在', 404);
    }

    // 检查是否已在书架中
    const [existingBookshelf] = await pool.query(
      'SELECT id FROM bookshelf WHERE user_id = ? AND book_id = ?',
      [userId, bookIdNum]
    );
    if (existingBookshelf.length > 0) {
      return error(res, '已在书架中', 400);
    }

    // 添加到书架
    await pool.query(
      'INSERT INTO bookshelf (user_id, book_id) VALUES (?, ?)',
      [userId, bookIdNum]
    );

    success(res, null, '添加成功');
  } catch (err) {
    console.error('添加书架失败:', err);
    if (err.code === 'ER_DUP_ENTRY') {
      return error(res, '已在书架中', 400);
    }
    next(err);
  }
};

exports.remove = async (req, res, next) => {
  try {
    const { bookId } = req.params;
    
    const [result] = await pool.query(
      'DELETE FROM bookshelf WHERE user_id = ? AND book_id = ?',
      [req.userId, bookId]
    );
    
    if (result.affectedRows === 0) {
      return error(res, '书架中无此书籍', 404);
    }
    
    success(res, null, '移除成功');
  } catch (err) {
    next(err);
  }
};